/**
 * Created by HaiHui on 2017/10/17.
 */
var table;
$(document).ready(function() {
	table = $('#roleManager').DataTable({
		"pagingType" : "simple_numbers",//设置分页控件的模式
		searching : false,//屏蔽datatales的查询框
		aLengthMenu : [10],//设置一页展示10条记录
		"bLengthChange" : false,//屏蔽tables的一页展示多少条记录的下拉列表
		"ordering" : false,//屏蔽排序
		"oLanguage" : { //对表格国际化
			"sLengthMenu" : "每页显示 _MENU_条",
			"sZeroRecords" : "没有找到符合条件的数据",
			//  "sProcessing": "&lt;img src=’./loading.gif’ /&gt;",
			"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
			"sInfoEmpty" : "木有记录",
			"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
			"sSearch" : "搜索：",
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "前一页",
				"sNext" : "后一页",
				"sLast" : "尾页"

			}
		},
		"processing" : true, //打开数据加载时的等待效果
		"serverSide" : true,//打开后台分页
		"ajax" : {
			"url" : "role/list",
			"dataSrc" : "aaData",
			"data" : function(d) {
				d.roleName = $('#selectRoleName').val();

			}
		},
		"columns": [{
			"data": "roleId",
			"visible": false
		    },
			{
				"data": "roleName",
				"title": "角色名称"
			},
			{
				"data": "role",
				"title": "角色类型"
			},
			{
				"data": "description",
				"title": "描述"
			},
			{
				"data": null,
				"title": "操作"
			}
		],
		"columnDefs" : [ {
			"targets" : -1,//操作按钮目标列
			"data" : null,
			"defaultContent": "<i title=\"详情\" class=\"dogo-js-search fa fa-search\"></i><i title=\"编辑\" class=\"dogo-js-edit fa fa-edit\"></i><i title=\"删除\" class=\"dogo-js-del fa fa-trash-o\"></i><i title=\"分配菜单\" class=\"dogo-js-set fa fa-bars" +
			"\"></i>"

		} ],

	});
	//查看
	$('#roleManager tbody').on('click', '.dogo-js-search', function() {
		var data = table.row($(this).parents('tr')).data();
		showDetail(data.roleId)
		// $('#search-modal').modal(data.prId);
	});
	//分配菜单
	$('#roleManager tbody').on('click', '.dogo-js-set', function() {
		var data = table.row($(this).parents('tr')).data();
		showSetDetail(data.roleId)
		// $('#search-modal').modal(data.prId);
	});
	//del
	$('#roleManager tbody').on('click', '.dogo-js-del', function() {
		var data = table.row($(this).parents('tr')).data();
		var confirmIdx = layer.confirm("确认要删除?", {
				btn: ['删除', '取消']
			},
			function() {
				var setting = {
					url: "role/delete",
					data: {
						roleId: data.roleId
					}
				}
				ajaxSubmit(setting, function(responseData) {
					checkSubmitResult(responseData, {
						error: "删除失败"
					}, function(responseData) {
						layer.alert(responseData.description);
						$('#roleManager').DataTable().ajax.reload();

					});
				}, "删除失败");
			},
			function() {
				layer.close(confirmIdx);
			});

	});
	//edit
	$('#roleManager tbody').on('click', '.dogo-js-edit', function() {

		var data = table.row($(this).parents('tr')).data();
		showEditModal(data.roleId);

	});
});

function search() {
	table.ajax.reload();

}

function showAddModal() {
	$("#modal-label").text("添加角色信息");
	$("#saveProjectInfo").text("添加");
	$("#saveProjectInfo").data("opType", "add");
	$("#roleId").val("");
	$("#roleName").val("");
	$("#role").val("");
	$("#description").val("");
	//$("#total").val("");
	//$("#dustRemark").val("");
	$('#edit-modal').modal();
	//initCombo('dePrid', '/xbermanager/projects/list', 'prId', 'prPrname');
}
var parentCategoryTree = null;
var treeValue=null;//存储树形的json数据
var ids = null;
function showSetDetail(roleId){
	debugger;
	$("#hideResId").val(roleId);
	var setting = {
		url: "res/resByRole",
		data: {
			roleId: roleId

		}
	}
	ajaxSubmit(setting, function(responseData) {
		checkSubmitResult(responseData, {
			error: "获取权限信息失败"
		}, function(responseData) {
			//TODO 详情页面数据填充
			ids = responseData.data;

			//$("#selectParent").modal("hide");//隐藏选择属性框
		});
	}, "获取权限信息失败");


	loadCategoryParent();//如果没有加载整个树，立即加载

	$("#selectParent").modal("show");//显示选择树形对话框


}
/**
 * 树组件操作，设置选中的树节点数据
 */
function setTreeSelectedValue(){

	if(ids==null){//空
		return;
	}
	parentCategoryTree.checkAllNodes(false);
	if(ids.length==1){//含一个id
		parentCategoryTree.checkNode(parentCategoryTree.getNodeByParam("id",ids),true);
	}else{
		for(var i=0;i<ids.length;i++){
			parentCategoryTree.checkNode(parentCategoryTree.getNodeByParam("id",ids[i]),true);
		}
	}
}
/**
 * 加载数据
 * @param roleId
 */
function loadCategoryParent(resId){
	var url = "res/getParent";
	var data = {};
	if(resId!=null){
		data["resId"] = resId ;
	}
	$.ajax({
		url:url,
		data:data,
		type:"post",
		dataType:"json",
		success:function(responseData){
			responseData = parseResponseData(responseData);
			//treeValue=responseData.obj;//将树结构中的数据复制到下拉框数据
			if(responseData!=null && responseData.result == true){
				initParentCategoryTree(responseData.data);
			} else {
				layer.alert("获取树结构失败！", {
					skin: 'layui-layer-molv',
					closeBtn: 0
				});
			}
		},
	});
}
function initParentCategoryTree(treeData) {
	var setting = {
		data : {
			simpleData : {
				enable : true
			}
		},
		check : {
			enable : true,
			chkStyle:"checkbox"
		}/*,
		 callback : {
		 onCheck : doSelectParent,
		 onClick : doSelectParent
		 }*/
	};
	parentCategoryTree = $.fn.zTree.init($("#pCategoryTree"), setting, treeData);
	setTreeSelectedValue();//将剩余选中含
	// 有的id号的树节点选中
}
/**
 *
 * 多选框的操作
 * 将获得的数据变成多选框已选择的值
 * 需要的参数是json格式
 */
function formatSelectValue(jsonValue){
	if(jsonValue==null||jsonValue.length==0){
		return;
	}else{
		var json="";
		for(var i=0;i<jsonValue.length;i++){
			var id= jsonValue[i].id;
			//var text= jsonValue[i].name;
			//json=json+"{'id':'"+id+"',"+"'text':'"+text+"'}&|";
			json = json+id+",";
		}
		return json.substring(0,json.length - 1);
		/*selectValue = json.substring(0,json.length-2).split("&|");
		for(var i=0;i<selectValue.length;i++){
			initMuljsons[i]=parseResponseData(selectValue[i]);
		}
		initMuljsons.length=selectValue.length;*/
	}
}

/**
 * 处理ajax返回数据，如果返回string, 处理成json格式
 */
function parseResponseData(responseData){
	if(typeof(responseData)=="string"){
		return eval("("+responseData+")");
	} else {
		return responseData;
	}
}
function showEditModal(dataId) {
	$("#modal-label").text("修改角色信息");
	$("#saveProjectInfo").text("修改");
	$("#saveProjectInfo").data("opType", "edit");
	var setting = {
		url: "role/detail",
		data: {
			roleId: dataId
		}
	}
	ajaxSubmit(setting, function(responseData) {
		checkSubmitResult(responseData, {
			error: "获取角色信息失败"
		}, function(responseData) {
			//TODO 详情页面数据填充
			var data = responseData.data;
			$("#roleId").val(data.roleId);
			$("#roleName").val(data.roleName);
			$("#role").val(data.role);
			$("#description").val(data.description);



			$("#edit-modal").modal('show');
		});
	}, "获取角色信息失败");

}
/**
 * 树组件操作,获取选中的树节点数据
 */
function getTreeSelectedValue(){
	if(parentCategoryTree==null||parentCategoryTree==""){
		return ;
	}else{
		return treeSelectedValue=parentCategoryTree.getCheckedNodes(true);
	}
}
$("#confirmTree").click(function(){

	//getTreeSelectedValue();//获取树节点选中值

	//格式化为json
	var resId =formatSelectValue(getTreeSelectedValue());


	var roleId = $("#hideResId").val();


	var setting = {
		url: "role/roleRes",

		data: {
			roleId: roleId,
			resId:resId
		}
	}
	ajaxSubmit(setting, function(responseData) {
		checkSubmitResult(responseData, {
			error: "获取角色信息失败"
		}, function(responseData) {
			//TODO 详情页面数据填充
			//var data = responseData.data;
			layer.open({
				content: responseData.description,
				success: function(layero, index){
					$("#selectParent").modal("hide");//隐藏选择属性框
				}
			});


		});
	}, "获取角色信息失败");


});

function showDetail(dataId) {
	var setting = {
		url: "role/detail",

		data: {
			roleId: dataId
		}
	}
	ajaxSubmit(setting, function(responseData) {
		checkSubmitResult(responseData, {
			error: "获取角色信息失败"
		}, function(responseData) {
			//TODO 详情页面数据填充
			var data = responseData.data;
			$("#search-modal").find("#infoRoleName").text(data.roleName);
			$("#search-modal").find("#infoRole").text(data.role);
			$("#search-modal").find("#infoDescription").text(data.description);

			$("#search-modal").modal('show');
		});
	}, "获取角色信息失败");
}
//添加、修改项目
$("#saveProjectInfo").click(function() {
	var opType = $(this).data("opType");
	var action = null;
	var formdata = {};
	formdata = $("#editForm").serializeJson();
	var errorMsg = null;

	if(opType == "add") {
		action = "role/add";
		errorMsg = "添加信息失败";
	} else if(opType == "edit") {
		action = "role/update";
		errorMsg = "修改信息失败";
	}

	if(action == null) {
		layer.alert("不支持的操作类型");
	} else {
		debugger;
		var setting = {
			url: action,
			data: JSON.stringify(formdata),
			cache: false,
			contentType: "application/json",
			processData: false,
			async: false

		}
		ajaxSubmit(setting, function(responseData) {
			checkSubmitResult(responseData, {
				error: errorMsg
			}, function(responseData) {
				$("#edit-modal").modal('hide');
				layer.alert(responseData.description);
				$('#roleManager').DataTable().ajax.reload();

			});

		}, errorMsg);

	}
});